package org.example.mybatisplus.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class LockController {

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/testLock")
    public String testLock() {
        // 获取锁对象，"myLock" 是锁的 key
        RLock lock = redissonClient.getLock("myLock");
        boolean isLocked = false;

        try {
            // 尝试获取锁，等待时间 10 秒，锁租期 60 秒
            isLocked = lock.tryLock(10, 60, TimeUnit.SECONDS);
            if (isLocked) {
                // 成功获取锁，执行业务逻辑
                System.out.println("Lock acquired, processing...");
                Thread.sleep(5000); // 模拟业务处理
                return "Operation completed successfully!";
            } else {
                // 未获取到锁
                return "Failed to acquire lock!";
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return "Operation interrupted!";
        } finally {
            // 释放锁（仅在获取锁的情况下释放）
            if (isLocked) {
                lock.unlock();
                System.out.println("Lock released!");
            }
        }
    }
}